package my.jieh.tips.util.regex;

/**
 * <p>Title: Core Java Technologies Tech Tips</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: Blueimp</p>
 * @author jieh
 * @version 1.0
 */
import java.util.regex.*;

public class GroupDemo3 {
  static final String stringlist[] = {
    "abc 123 def   456",
    "789 ghi",
    "no match",
    "jkl978mno   678",
    "",
    "123.256",
    "1,2,3,4,5,6,7,8,9,10"
  };

  public static void main(String args[]) {

    // compile regular expression pattern for
    // a number consisting of one or more
    // digits

    Pattern patt = Pattern.compile("(\\d+)");

    for (int i = 0; i < stringlist.length; i++) {
      String currstr = stringlist[i];

      String outstr;

      // see if the current string has
      // a match

      Matcher match = patt.matcher(currstr);
      boolean result = match.find();

      // if found a match, then go through
      // string and replace all matches with
      // "[matchstring]"

      if (result) {
        StringBuffer strbuf = new StringBuffer();
        do {
          match.appendReplacement(strbuf, "[$1]");
          String s = match.group();
          result = match.find();
        } while (result);
        match.appendTail(strbuf);
        outstr = strbuf.toString();
      // if no match, just point output at input
      } else {
        outstr = currstr;
      }

      // display the result

      System.out.println(outstr);
    }
  }
}
